﻿using System;
using System.IO;
using System.Net.Http;
using System.Net;
using System.Threading.Tasks;

namespace Yxinmt.Windows.Meeting
{
    public class ProgressableHttpContent : HttpContent
    {
        private readonly HttpContent _content;
        private readonly Action<long, long> _progressCallback;
        private readonly int _bufferSize;

        public ProgressableHttpContent(HttpContent content, int bufferSize, Action<long, long> progressCallback)
        {
            _content = content;
            _bufferSize = bufferSize;
            _progressCallback = progressCallback;
        }

        protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            var buffer = new byte[_bufferSize];
            long totalBytes = _content.Headers.ContentLength ?? 0;
            long bytesSent = 0;

            using (var contentStream = await _content.ReadAsStreamAsync())
            {
                int readBytes;
                while ((readBytes = await contentStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                {
                    await stream.WriteAsync(buffer, 0, readBytes);
                    bytesSent += readBytes;
                    _progressCallback?.Invoke(bytesSent, totalBytes);
                }
            }
        }

        protected override bool TryComputeLength(out long length)
        {
            length = _content.Headers.ContentLength ?? 0;
            return true;
        }
    }
}
